package com.yunbiao.ybbusstopplate.ui.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.SurfaceTexture;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.TextureView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ConvertUtils;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

public class ScrollTextView2 extends TextureView {

    private final int speed = 20;
    private final Paint paint;
    private final StringBuffer stringBuffer;
    private final ScheduledExecutorService scheduledExecutorService;
    private final AtomicBoolean isUpdated;

    public ScrollTextView2(@NonNull Context context) {
        this(context, null);
    }

    public ScrollTextView2(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, -1);
    }

    public ScrollTextView2(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

        isUpdated = new AtomicBoolean(false);

        stringBuffer = new StringBuffer();

        paint = new Paint();
        paint.setColor(Color.RED);
        paint.setTextSize(ConvertUtils.sp2px(350));
        paint.setFlags(Paint.ANTI_ALIAS_FLAG);
        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);

        setOpaque(true);

        setSurfaceTextureListener(surfaceTextureListener);
    }

    public void setText(String string){
        stringBuffer.setLength(0);
        stringBuffer.append(string);
        isUpdated.set(true);
    }

    private float textWidth = 0;
    private float viewWidth_plus_textLength = 0;
    private float textX = 0;
    private Paint.FontMetrics fontMetrics;
    private float distance = 0;
    private float textY = 0;

    private final SurfaceTextureListener surfaceTextureListener = new SurfaceTextureListener() {
        @Override
        public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) {
            scheduledExecutorService.scheduleAtFixedRate(() -> {
                String string = stringBuffer.toString();

                if(isUpdated.get()){
                    textWidth = paint.measureText(string);
                    viewWidth_plus_textLength = width + textWidth;
                    textX = -width + (width >> 1);

                    fontMetrics = paint.getFontMetrics();
                    distance = (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom;
                    textY = (height >> 1) + distance;
                    isUpdated.set(false);
                }

                if(TextUtils.isEmpty(string)){
                    return;
                }

                if (isAvailable() && !Thread.currentThread().isInterrupted()) {
                    Canvas canvas = lockCanvas();
                    if(canvas != null){
                        canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
                        canvas.drawColor(Color.BLACK);
                        if(!TextUtils.isEmpty(string)){
                            if(textWidth < width){
                                canvas.drawText(string, (width - textWidth) / 2, textY,  paint);
                            } else {
                                canvas.drawText(string, width - textX, textY,  paint);

                                textX += speed;
                                if (textX > viewWidth_plus_textLength) {
                                    textX = 0;
                                }
                            }
                        }
                        unlockCanvasAndPost(canvas);
                    }
                }
            }, 500, 33, TimeUnit.MILLISECONDS);
        }

        @Override
        public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width, int height) {

        }

        @Override
        public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface) {
            scheduledExecutorService.shutdownNow();
            return true;
        }

        @Override
        public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) {

        }
    };
}
